package kr.hkit.powerjava.chther26.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import kr.hkit.powerjava.chther26.common.ConnectionFactory;
import kr.hkit.powerjava.chther26.common.DbUtil;
import kr.hkit.powerjava.chther26.dto.Department;

public class DepartmentDAO implements DaoInterface<Department>{
	private Connection connection;
	private PreparedStatement pstmt;

	@Override
	public void insertItem(Department item) throws SQLException {
		String sql = "insert into department values(?,?,?)";
		connection = ConnectionFactory.getConnection();
		pstmt = connection.prepareStatement(sql);
		pstmt.setInt(1, item.getDeptNo());
		pstmt.setString(2, item.getDeptName());
		pstmt.setInt(3, item.getFloor());
		pstmt.executeUpdate();
		DbUtil.close(pstmt);
		
	}

	@Override
	public void deleteItemByNo(Department item) throws SQLException {
		String sql = "delete from department where deptno= ?";
		pstmt = connection.prepareStatement(sql);
		pstmt.setInt(1, item.getDeptNo());
		pstmt.executeUpdate();
		DbUtil.close(pstmt);
	}

	@Override
	public void updateItemByNo(Department item) throws SQLException {
		String sql = "update department set deptname=?,floor=? where deptno=?"; 
		pstmt = connection.prepareStatement(sql);
		pstmt.setString(1, item.getDeptName());
		pstmt.setInt(2, item.getDeptNo());
		pstmt.setInt(3, item.getFloor());
		pstmt.executeUpdate();
		DbUtil.close(pstmt);
	}

	@Override
	public ArrayList<Department> listItems() throws SQLException {
		ArrayList<Department> list = new ArrayList<>();
		String sql ="select deptno,deptname,floor from department";
		pstmt = connection.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		while(rs.next()){
			list.add(new Department(
					rs.getInt("deptno"),
					rs.getString("deptname"),
					rs.getInt("floor")));
		}
		
		DbUtil.close(rs);
		DbUtil.close(pstmt);
		return list;
	}

	

	@Override
	public Department searchItem(Department item) throws SQLException {
		Department department = null;
		String sql = "select deptno,deptname,floor from department where deptno=?";
		pstmt = connection.prepareStatement(sql);
		pstmt.setInt(1, item.getDeptNo());
		ResultSet rs = pstmt.executeQuery();
		if(rs.next()) {
			department = new Department();
			department.setDeptNo(rs.getInt(1));
			department.setDeptName(rs.getString(2));
			department.setFloor(rs.getInt(3));
		}
		return department;
	}

	public DepartmentDAO(Connection connection) {
		this.connection = connection;
	}

}
